from rasa_sdk.types import DomainDict
from typing import Dict, Text, Any, List, Union
from flask import jsonify
from rasa_sdk import Tracker, Action
from rasa_sdk.events import UserUtteranceReverted, Restarted, SlotSet, EventType
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.forms import FormAction
# from actions import ChatApis
# from actions.WeatherApis import get_weather_by_day
from requests import (
    ConnectionError,
    HTTPError,
    TooManyRedirects,
    Timeout
)
# from test.qachat import get_qa
from rasa_sdk import ActionExecutionRejection
from rasa_sdk.events import SlotSet, AllSlotsReset
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.forms import FormAction, REQUESTED_SLOT
import requests, random, math
import re
import json
# import jieba
import logging

logger = logging.getLogger(__name__)

class action_weather_init(Action):
    def name(self) -> Text:
        return 'action_weather_init'

    def run(self, dispatcher, tracker, domain):
        dispatcher.utter_message('进入天气查询模式：小安提醒您，天气查询目前只支持今天、明天、后天这三天查询哟')
        return [AllSlotsReset()]

## 查询天气
class QueryWeather(FormAction):
    def __init__(self):
        super().__init__()
        # 天气查询私钥
        self.KEY = '你的私钥'
        self.LOCATION = 'beijing'  # 所查询的位置，可以使用城市拼音、v3 ID、经纬度等
        self.url = '心知天气api'  # API URL，可替换为其他 URL
        self.UNIT = 'c'  # 单位
        self.LANGUAGE = 'zh-Hans'  # 查询结果的返回语言
        self.data={
            'key': self.KEY,
            'location': self.LOCATION,
            'language': self.LANGUAGE,
            'unit': self.UNIT,
            'start': 0,
            'days': 10
        }
        # 0 代表今天,1 代表明天,2代表后天
        self.num = 0

    def name(self) -> Text:
        return "weather_form"

    @staticmethod
    def required_slots(tracker):
        return ['datetime','address']


    def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict[Text, Any]]]]:
        return {'datetime':[self.from_text()],'address':[self.from_text()]}


    def validate_datetime(self,slot_value, dispatcher, tracker, domain):
        d_list = ['今天','明天','后天']
        if slot_value in d_list:
        # if slot_value in d_:
            return {"datetime":slot_value}
        else:
            dispatcher.utter_message('暂不支持查询{}的天气'.format(slot_value))
            return {"datetime":None}

    def validate_address(self,slot_value, dispatcher, tracker, domain):
        # list=['北京','上海','深圳','广州']
        #path = '/home/zhongshan/rasa_copy/rasa/data/flie_txt/cityname.txt'

        path = '../data/file_txt/cityname.txt'
        d_ = [i.strip() for i in open(path, 'r').readlines()]
        # if slot_value in list:
        if slot_value in d_:
            return {"address":slot_value}
        else:
            dispatcher.utter_message('您输入的不是地名哟')
            return {"place":None}

    def submit(self,dispatcher, tracker, domain):
        date = tracker.get_slot('datetime')
        address = tracker.get_slot('address')
        print(address)
        self.judge_time(date)
        text_day, text_night, high, low, wind_direction, humidity, wind_speed, wind_scale,date_ = self.get_weather(address)
        s='{}{}({})的天气情况是：白天{},晚上{}.当天最高温度是{}摄氏度,最低温度是{}摄氏度.'.format(
           address,date,date_, text_day,text_night,high,low)
        s2 = self.get_suggestion(address,date)
        dispatcher.utter_message('小娜为您查询到：')
        dispatcher.utter_message(s+s2)

        # return [AllSlotsReset()]
        return [Restarted()]


    def judge_time(self,date):
        if date == '今天':
            self.num = 0
        elif date == '明天':
            self.num = 1
        elif date == '后天':
            self.num = 2


    def get_weather(self,address):
        self.LOCATION = address
        str_ = requests.get(url=self.url,params=self.data,timeout=2).text
        dic = json.loads(str_)
        print(dic)
        # 白天天气
        text_day = dic['results'][0]['daily'][self.num]['text_day']
        # 夜晚天气
        text_night = dic['results'][0]['daily'][self.num]['text_night']
        # 最高温度
        high = dic['results'][0]['daily'][self.num]['high']
        # 最低温度
        low = dic['results'][0]['daily'][self.num]['low']
        # 风向
        wind_direction = dic['results'][0]['daily'][self.num]['wind_direction']
        # 湿度（百分比）
        humidity = dic['results'][0]['daily'][self.num]['humidity']
        # 风速
        wind_speed = dic['results'][0]['daily'][self.num]['wind_speed']
        # 风力等级
        wind_scale = dic['results'][0]['daily'][self.num]['wind_scale']
        # 日期
        date_ = dic['results'][0]['daily'][self.num]['date']

        return text_day,text_night,high,low,wind_direction,humidity,wind_speed,wind_scale,date_

    def get_suggestion(self,address,date):
        url = 'https://api.seniverse.com/v3/life/suggestion.json?key=你的私钥&location={}&language=zh-Hans&unit=c&start=1&days=3'.format(address)
        str_ = requests.get(url=url, timeout=2).text
        tip_list = json.loads(str_)['results']
        d = tip_list[0]['suggestion'][self.num]
        # 空气污染
        air_pollution = d['air_pollution']
        #
        # air_pollution_text = '空气等级为：' + air_pollution['brief'] + ',' + air_pollution['details']
        air_pollution_text = air_pollution['details']

        # # 穿着打扮
        # dressing = d['dressing']
        # dressing_text = '穿着打扮：' + dressing['brief'] + ',' + dressing['details'] + '\n'

        # 穿着打扮
        dressing = d['dressing']
        dressing_text = dressing['details']

        # # 紫外线
        # uv = d['uv']
        # uv_text = '紫外线：' + uv['brief'] + ',' + uv['details'] + '\n'

        # 紫外线
        uv = d['uv']
        uv_text = uv['details']

        # sport运动
        # sport = d['sport']
        # sport_text = '运动：' + sport['brief'] + ',' + sport['details'] + '\n'
        sport = d['sport']
        sport_text = sport['details']

        # mood 心情
        mood = d['mood']
        mood_text = mood['details']

        # # mood 心情
        # mood = d['mood']
        # mood_text = '心情：' + mood['brief'] + ',' + mood['details'] + '\n'

        # # 交通
        # traffic = d['traffic']
        # traffic_text = '交通：' + traffic['brief'] + ',' + traffic['details'] + '\n'

        # 交通
        traffic = d['traffic']
        traffic_text = traffic['details']

        # # 洗车
        # car_washing = d['car_washing']
        # car_washing_text = '洗车：' + car_washing['brief'] + ',' + car_washing['details'] + '\n'

        # 洗车
        car_washing = d['car_washing']
        car_washing_text = car_washing['details']

        # # 雨伞
        # umbrella = d['umbrella']
        # umbrella_text = '雨伞：' + umbrella['brief'] + ',' + umbrella['details'] + '\n'

        # 雨伞
        umbrella = d['umbrella']
        umbrella_text = umbrella['brief']
        su_list = [air_pollution_text,dressing_text,uv_text,sport_text,mood_text,traffic_text,car_washing_text,umbrella_text]

        return '小娜给您提点生活建议'+ random.sample(su_list,1)[0]